<!--
 * @Descripttion:
 * @Author: Silence
 * @Date: 2023-05-25 19:32:16
 * @LastEditors: Silence
 * @LastEditTime: 2023-05-25 21:35:07
-->
<template>
  <div>
    <div class="add"><button @click="add">新增</button></div>
    <ItemBox :list="list">
      <template #look="obj1">
        <button @click="Model(obj1.obj)">编辑</button>
        <button @click="del(obj1.obj.id)">删除</button>
      </template>
    </ItemBox>
    <DialogBox :Showflag.sync="Showflag" :title="title">
      <template>
        <form>
          书名:<input type="text" v-model="fromData.bookname" /><br />
          出版社:<input type="text" v-model="fromData.publisher" /><br />
          作者:<input type="text" v-model="fromData.author" />
        </form>
        <div class="btns">
          <button @click="Showflag = false">取消</button>
          <button @click="submit">确认</button>
        </div>
      </template>
    </DialogBox>
  </div>
</template>
<script>
import ItemBox from './components/ItemBox.vue'
import DialogBox from './components/DialogBox.vue'
export default {
  components: {
    ItemBox,
    DialogBox
  },
  data () {
    return {
      title: '',
      fromData: {
        bookname: '',
        publisher: '',
        author: '',
        createdAt: new Date().toLocaleString(),
        updatedAt: new Date().toLocaleString()
      },
      Showflag: false,
      list: [

      ]
    }
  },
  async created () {
    const res = await this.$axios.get('http://ajax-api.itheima.net/api/books')
    // console.log(res.data.data)
    this.list = res.data.data
    console.log(this.fromData)
  },
  watch: {
    list () {
      this.render()
    }
  },
  computed: {
  },
  methods: {
    async render () {
      const res = await this.$axios.get('http://ajax-api.itheima.net/api/books')
      this.list = res.data.data
    },
    del (id) {
      this.$axios.delete('http://ajax-api.itheima.net/api/books/' + id)
    },
    Model (obj) {
      this.Showflag = true
      this.title = '编辑数据'
      this.fromData = JSON.parse(JSON.stringify(obj))
    },
    submit () {
      const { bookname, author, publisher } = this.fromData
      if (this.fromData.id) {
        this.$axios.put('http://ajax-api.itheima.net/api/books/' + this.fromData.id, { bookname, author, publisher })
      } else {
        this.$axios.post('http://ajax-api.itheima.net/api/books', { bookname, author, publisher })
      }
      this.Showflag = false
      this.fromData = {
        bookname: '',
        publisher: '',
        author: '',
        createdAt: new Date().toLocaleString(),
        updatedAt: new Date().toLocaleString()
      }
    },
    add () {
      this.Showflag = true
      this.title = '添加数据'
    }
  }
}
</script>
<style lang='less'  scoped>
.add {
  text-align: center;
  margin-top: 50px;
}
.add button {
  width: 80px;
  height: 50px;
  font-size: 20px;
}
</style>
